package com.stu.utils;

import com.google.common.base.Strings;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

public class ImgUtils {

    /**
     * 图片转base64
     *
     * @param imgPath
     * @return
     * @throws IOException
     */
    public static String Image2Base64(String imgPath) throws IOException {
        byte[] bytes = FileUtils.readFileToByteArray(new File(imgPath));
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 把base64转化为文件.
     *
     * @param base64   base64
     * @param filePath 目标文件路径
     */
    public static Boolean decryptByBase64(String base64,String filePath) {
        if (Strings.isNullOrEmpty(base64) && Strings.isNullOrEmpty(filePath)) {
            return Boolean.FALSE;
        }
        try {
            Files.write(Paths.get(filePath),Base64.decodeBase64(base64.substring(base64.indexOf(",") + 1)),StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Boolean.TRUE;
    }
}
